<?php
/**
 * Description: 获取任务收藏列表
 * User: devforma
 * Date: 15/1/7
 * Time: 16:30
 */

class GetCollectedTasks implements iController {

    private $userIdField, $userId, $taskType = array();

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;
        
        // 检查offset
        if (!is_numeric($queryArgs['offset']) || $queryArgs['offset']<0) {
            return genOutput(1000);
        }
        
        // 检查count
        if (!is_numeric($queryArgs['count']) || $queryArgs['count']<1) {
            return genOutput(1000);
        }
        
        // 检查order
        if (!in_array($queryArgs['order'], array('asc','desc'))) {
            return genOutput(1000);
        }
        
        // 验证用户有效性
        $u = validateUser($queryArgs);
        if ($u==0) return genOutput(1000);

        if ($u == 1) {
            $this->userIdField = 'user_id';
            $this->userId = $queryArgs['user_id'];
        } elseif ($u == 2) {
            $this->userIdField = 'guest_id';
            $this->userId = $queryArgs['guest_id'];
        } else {
            return genOutput(1000);
        }
        
        //获取任务类型设置
        $taskTypeData = $uddb->getResults("SELECT * FROM `{$uddb->confPlanType}` WHERE 1");
        foreach ($taskTypeData as $row) {
            $this->taskType["$row->type_id"] = $row->type_name; //由type_id获取信息
            $this->taskType["$row->type_name"] = $row->type_id; //由名称获取信息
        }
        
        $sql = "SELECT * FROM `{$uddb->collection}`
                WHERE `{$this->userIdField}`=:user
                ORDER BY `collect_time` {$queryArgs['order']}
                LIMIT :offset, :count";
        $tasks = $uddb->getResults($sql,
                                   array(':user' => $this->userId,
                                         ':offset' => intval($queryArgs['offset']),
                                         ':count' => intval($queryArgs['count'])
                                         )
                                   );

        $list = array();
        if (!empty($tasks)) {
            foreach ($tasks as $task) {
                $list[] = array(
                    'task_id' => intval($task->mission_id),
                    'title' => $task->mission_title,
                    'subtitle' => '',
                    'type' => $this->taskType["$task->mission_type"],
                    'content_id' => intval($task->mission_content_id),
                    'content' => json_decode($task->mission_content) ? '' : $task->mission_content,
                    'date' => $task->collect_time,
                    'done' => true
                );
            }
        }

        return genOutput(1, array('tasks' => $list));
    }
}
